package com.zhouyou.http.demo.slice;

import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.body.UIProgressResponseCallBack;
import com.zhouyou.http.callback.ProgressDialogCallBack;
import com.zhouyou.http.demo.ResourceTable;
import com.zhouyou.http.model.utils.FileUtils;
import com.zhouyou.http.model.utils.ToastUtils;
import com.zhouyou.http.demo.view.HorizontalProgressDialog;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.subsciber.IProgressDialog;
import com.zhouyou.http.utils.HttpLog;
import com.zhouyou.http.view.CancelableDialog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import okhttp3.MediaType;

import java.io.*;

import static com.zhouyou.http.demo.constant.AppConstant.*;

public class UploadAbilitySlice extends AbilitySlice {
    private  String ressult="";
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_upload);
        findComponentById(ResourceTable.Id_btn_uploade_file).setClickedListener(component -> {
                    try {
                        onUploadFile();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );
        findComponentById(ResourceTable.Id_btn_updload_inputstream).setClickedListener(component -> {
            try {
                onUploadInputStream();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        findComponentById(ResourceTable.Id_btn_upload_bytes).setClickedListener(component -> {

            try {
                onUploadBytes();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        findComponentById(ResourceTable.Id_btn_upload_file_maps).setClickedListener(component -> {

            onUploadFileMaps();

        });
        findComponentById(ResourceTable.Id_btn_upload_file_map2).setClickedListener(component -> {
            onUploadFileMaps2();
        });
        findComponentById(ResourceTable.Id_btn_upload_one).setClickedListener(component -> {
            onUploadOne();
        });



    }

    private HorizontalProgressDialog dialog;

    public HorizontalProgressDialog getDialog() {
        return dialog;
    }

    private IProgressDialog mProgressDialog = new IProgressDialog() {
        @Override
        public CancelableDialog getDialog() {
            if (dialog == null) {
                dialog = new HorizontalProgressDialog(UploadAbilitySlice.this);
                dialog.setMessage("正在上传...");
                // 设置提示的title的图标，默认是没有的，如果没有设置title的话只设置Icon是不会显示图标的
                dialog.setTitle("文件上传");
                dialog.setMax(100);
//                dialog.show();
            }
            return dialog;
        }
    };


    public void onUploadFile() throws Exception {

        final UIProgressResponseCallBack listener = new UIProgressResponseCallBack() {
            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.getInstance().e(progress + "% ");
                dialog.setProgress(progress);
                dialog.setMessage(progress + "%");
                if (done) {//完成
                    dialog.setMessage("上传完整");
                }
            }
        };
        File file = FileUtils.getDistributedDir(this, "1.jpg");
        EasyHttp.post(UPLOAD_FILE)
                //如果有文件名字可以不用再传Type,会自动解析到是image/*
                .params("avatar", file, file.getName(), listener)
                //.params("avatar", file, file.getName(),MediaType.parse("image/*"), listener)
                .accessToken(true)
                .timeStamp(true)
                .execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {
                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ressult=e.getMessage();
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(e.getMessage());
                    }

                    @Override
                    public void onSuccess(String response) {
                        ressult=response;
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(response);
                    }
                });

    }

    public void onUploadInputStream() throws Exception {
        final UIProgressResponseCallBack listener = new UIProgressResponseCallBack() {
            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.getInstance().e(progress + "% ");
                ((HorizontalProgressDialog) mProgressDialog.getDialog()).setProgress(progress);
                if (done) {//完成
                    ((HorizontalProgressDialog) mProgressDialog.getDialog()).setMessage("上传完整");
                }
            }
        };

        final InputStream inputStream = FileUtils.getRawFile(this, "1.jpg");
        EasyHttp.post(UPLOAD_FILE)
                .params("avatar", inputStream, "clife.png", listener)
                .accessToken(true)
                .timeStamp(true)
                .execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {
                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ressult=e.getMessage();
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(e.getMessage());
                    }

                    @Override
                    public void onSuccess(String response) {
                        ressult=response;
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(response);
                    }
                });
    }

    public void onUploadBytes() throws Exception {
        final UIProgressResponseCallBack listener = new UIProgressResponseCallBack() {
            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.getInstance().e(progress + "% ");
                ((HorizontalProgressDialog) mProgressDialog.getDialog()).setProgress(progress);
                if (done) {//完成
                    ((HorizontalProgressDialog) mProgressDialog.getDialog()).setMessage("上传完整");
                }
            }
        };


        final InputStream inputStream = FileUtils.getRawFile(this, "test.jpg");
        byte[] bytes = FileUtils.toByteArray(inputStream);

        //avatar:表示key
        //bytes:表示上传的字节内容
        //"streamfile.png" 表示图片名称
        //MediaType.parse("image/*") 类型 表示上传的是图片
        //listener 上传进度回调监听
        EasyHttp.post(UPLOAD_FILE)
                //.params("avatar",bytes,"streamfile.png",MediaType.parse("image/*"),listener)
                //如果有文件名字可以不用再传Type,会自动解析到是image/*
                .params("avatar", bytes, "streamfile.png", listener)
                .accessToken(true)
                .timeStamp(true)
                .execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {
                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ressult=e.getMessage();
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(e.getMessage());
                    }

                    @Override
                    public void onSuccess(String response) {
                        ressult=response;
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(response);
                    }
                });
    }

    public void onUploadFileMaps() {
        File file = new File(FileUtils.getDistDir(this) + "1.jpg");


        UIProgressResponseCallBack mUIProgressResponseCallBack = new UIProgressResponseCallBack() {
            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.getInstance().i("progress=" + progress);
                ((HorizontalProgressDialog) mProgressDialog.getDialog()).setProgress(progress);
                if (done) {//完成
                    ((HorizontalProgressDialog) mProgressDialog.getDialog()).setMessage("上传完整");
                }
            }
        };
        EasyHttp.post(UPLOAD_HEADIMG)
                .baseUrl(new StringBuffer(SCHEMA).append(ZIAO_DAO).append(API).toString())
                .params("uid", "4811420")
                .params("auth_key", "21f8d9bcc50c6ac1ae1020ce12f5f5a7")
                .params("avatar", file, file.getName(), mUIProgressResponseCallBack)
                .execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {
                    @Override
                    public void onSuccess(String response) {
                        ressult=response;
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(response);
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ressult=e.getMessage();
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(e.getMessage());
                    }
                });

    }


    public void onUploadFileMaps2() {
        File file = new File(FileUtils.getDistDir(this) + "1.jpg");
        UIProgressResponseCallBack mUIProgressResponseCallBack = new UIProgressResponseCallBack() {
            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.getInstance().i("progress=" + progress);
                ((HorizontalProgressDialog) mProgressDialog.getDialog()).setProgress(progress);
                if (done) {//完成
                    ((HorizontalProgressDialog) mProgressDialog.getDialog()).setMessage("上传完整");
                }
            }
        };
        EasyHttp.post(new StringBuffer(SCHEMA).append(UPlOAD_ID).append(DJ_ADD_CARE).toString())
                .params("uid", "1")
                .params("title", "冷小菜")
                .params("content", "我发个哈哈哈哈哈哈哈哈")
                .params("key", "dangjian")
                .params("imgs[]", file, file.getName(), MediaType.parse("image/*"), mUIProgressResponseCallBack)
                .params("imgs[]", file, file.getName(), MediaType.parse("image/*"), mUIProgressResponseCallBack)
                .params("imgs[]", file, file.getName(), MediaType.parse("image/*"), mUIProgressResponseCallBack)
                .execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {
                    @Override
                    public void onSuccess(String response) {
                        ressult=response;
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(response);
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ressult=e.getMessage();
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(e.getMessage());
                    }
                });

    }



    public void onUploadOne( ) {
        File file = new File(FileUtils.getDistDir(this) + "1.jpg");
        UIProgressResponseCallBack mUIProgressResponseCallBack = new UIProgressResponseCallBack() {
            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                int progress = (int) (bytesRead * 100 / contentLength);
                HttpLog.getInstance().i("progress=" + progress);
                ((HorizontalProgressDialog) mProgressDialog.getDialog()).setProgress(progress);
                if (done) {//完成
                    ((HorizontalProgressDialog) mProgressDialog.getDialog()).setMessage("上传完整");
                }
            }
        };
        EasyHttp.post(UPLOAD_IMAG)
                .baseUrl(new StringBuffer(SCHEMA).append(UPLOAD_URL).toString())
                .params("img", file, file.getName(), mUIProgressResponseCallBack)
                .execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) {
                    @Override
                    public void onSuccess(String s) {
                        ressult=s;
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(s);
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ressult=e.getMessage();
                        ToastUtils.getInstance(UploadAbilitySlice.this).showToast(e.getMessage());
                    }
                });
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }


    public String getResult() {
        return ressult;
    }
}
